package com.neusoft.EYSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.EYSystem.dao.ClientDAO;
import com.neusoft.EYSystem.dao.UserOfClientDAO;
import com.neusoft.EYSystem.po.Client;
import com.neusoft.EYSystem.po.ResponseBean;
import com.neusoft.EYSystem.po.UserOfClient;
import com.neusoft.EYSystem.service.UserOfClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserOfClientServiceImpl implements UserOfClientService {

    @Autowired
    private UserOfClientDAO userOfClientDAO;

    @Autowired
    private ClientDAO clientDAO;

    @Override
    public ResponseBean<UserOfClient> getUser(UserOfClient userOfClient) {
        ResponseBean<UserOfClient> responseBean = new ResponseBean<>();
        String un = userOfClient.getUsername();
        UserOfClient user = userOfClientDAO.selectOne(new QueryWrapper<UserOfClient>().eq("username", un));
        if (user != null){
            if (user.getPassword().equals(userOfClient.getPassword())) {
                responseBean.setStatus(200);
                responseBean.setMsg("登录成功");
                responseBean.setData(user);
            } else {
                responseBean.setStatus(500);
                responseBean.setMsg("密码错误");
            }
        } else {
            List<Client> clients = clientDAO.getClient(un);
            List<Integer> clientIds = clients.stream().map(Client::getClientId).toList();
            if(clientIds.isEmpty()){
                responseBean.setStatus(500);
                responseBean.setMsg("姓名或者手机号或者身份证号或者昵称皆输入错误，请检查");
            } else {
                for( Integer clientId : clientIds) {
                    user = userOfClientDAO.selectOne(new QueryWrapper<UserOfClient>().eq("client_id", clientId));
                    if (user != null && user.getPassword().equals(userOfClient.getPassword())) {
                        responseBean.setStatus(200);
                        responseBean.setMsg("登录成功");
                        responseBean.setData(user);
                        return responseBean;
                    }
                }
                responseBean.setStatus(500);
                if (user == null) {
                    responseBean.setMsg("姓名或者手机号或者身份证号或者昵称皆输入错误，请检查");
                } else {
                    responseBean.setMsg("密码错误");
                }
            }
        }
        return responseBean;
    }
}
